package com.ikun.hosuserservice.controller;

import com.ikun.common.entity.ResponseResult;
import com.ikun.common.entity.ResponseStatus;
import com.ikun.hosuserservice.utils.validatecode.IVerifyCodeGen;
import com.ikun.hosuserservice.utils.validatecode.SimpleCharVerifyCodeGenImpl;
import com.ikun.hosuserservice.utils.validatecode.VerifyCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 验证码
 */
@RestController
@Slf4j
@RequestMapping("code")
public class Captcha {

    private String isCode ;

    @GetMapping("/verifyCode")
    public void verifyCode(HttpServletRequest request, HttpServletResponse response) {
         IVerifyCodeGen iVerifyCodeGen = new SimpleCharVerifyCodeGenImpl();
        try {
            //设置长宽
            VerifyCode verifyCode = iVerifyCodeGen.generate(80, 28);
            String code = verifyCode.getCode();
            isCode = code;
            log.info(code);
            //将VerifyCode绑定session
            request.getSession().setAttribute("VerifyCode", code);
            //设置响应头
            response.setHeader("Pragma", "no-cache");
            //设置响应头
            response.setHeader("Cache-Control", "no-cache");
            //在代理服务器端防止缓冲
            response.setDateHeader("Expires", 0);
            //设置响应内容类型
            response.setContentType("image/jpeg");
            response.getOutputStream().write(verifyCode.getImgBytes());
            response.getOutputStream().flush();
        } catch (IOException e) {
            log.info("", e);
        }
    }

    @GetMapping("/verification")
    public ResponseResult verification(@RequestParam String code) {
        if (isCode.equalsIgnoreCase(code)){
            /*验证成功,返回成功*/
            return ResponseResult.ok(ResponseStatus.OK);
        }else {
            return ResponseResult.error(ResponseStatus.BUSINESS_ERROR);
        }


    }
}
